var app = getApp();
import { api, util, dialog} from '../../../../js/util'
import { router } from '../../../../js/router'
import { retreat } from "../../../../js/modules/order.js"
import { finance } from "../../../../js/modules/store.js"
import {
  wholesaleSettings
} from "../../../../js/modules/gloab";
import BasePage from '../../../../js/common/base-page'
import {upload} from '../../../../js/modules/material.js'
import {detail} from "../../../../js/modules/mall.js";
BasePage({
  pageKey:"applyRetreat",

  /**
   * 页面的初始数据
   */
  data: {
    imgDomain: api.imgDomain,
    enableOss: api.enableOss,
    retreatInfo:{},
    goodslist: [],
    retreatTypeId:0,
    retreatType: ['退货', '换货'],
    isReturn: true,
    backWayArray: ["请选择", "退款至预存款余额", "退款至银行卡"],//0退款至余额,1退款至银行卡,2原路还回，3退款至授信账户--账户余额
    backWayIndex: 0,
    backWayList:[],
    rewayArray:[],//退货退款类型
    rewayIndex:0,
    showFooter: true,
    reasonList:[],
    reasonArray:[],
    reasonIndex:0,
    reason: '',
    caculate_info:{
      payable_price:0
    },
    account:null,
    isBacktrack:false,//是否原路
    quantityDigits: 2,//数量显示位数
    priceDigits: 2, //价格显示位数
    unitIndex:0,
    unitArray:['个','箱'],
    Currency:'',//货币符号
    RefundChannel:-1,
    bankArray:[],//银行账户
    bankList:[],
    bankIndex:0,
    alipayArray:[],//支付宝账号
    alipayList:[],
    alipayIndex:0,
    wechatArray:[],//微信账号
    wechatList:[],
    wechatIndex:0,
    switch:0,//开关-默认账号
    status:1,//开关-状态
    accountName:'',// 支付宝-微信账号
    ImgSrc:'',//上传图片
    showImg:'',//显示图片
    modelAccount:false,//添加账号
    userName:'',//姓名
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var oddNumber = decodeURIComponent(options.oddNumber);
    this.data.oddnumber = oddNumber;
    this.getWholesaleConfig();
    this.getDetail(oddNumber);
  },
  /**
   * 获得详情
   */
  getDetail: function (oddNumber) {
    var that=this;
    retreat.getOrderNew(oddNumber, that.data.Currency,function (res, orderid){
      var retreatInfo = res.Content || {};
      var goodslist = retreatInfo.OrderItems;
      var backWayList = retreatInfo.Channel||[];//退款渠道
      backWayList.unshift({Id:-1, Name:'请选择', Checked: 0});
      var backWayArray = [], backWayIndex = 0, refundChannel = -1;
      for(var i = 0;i<backWayList.length;i++){
        backWayArray.push(backWayList[i].Name);
        if (backWayList[i].Checked == 1) {
          backWayIndex = i;
          refundChannel = backWayList[i].Id;
        }
      }
      var reasonList = retreatInfo.RetreatReason||[];//详细原因描述
      reasonList.unshift({Id:-1,Reason:'请选择'});
      let reasonArray=[];
      for(var i=0;i<reasonList.length;i++){
        reasonArray.push(reasonList[i].Reason)
      }
      // 后台传回的商品价格不一定正确，需要取用内部的价格数据
      goodslist = goodslist.map((item) => {
        if (item.auxiliaryunits) {
          let list = item.auxiliaryunits
          for (let i in list) {
            if (list[i].Translated == item.AuxRate && list[i].Name == item.AuxUnit) {
              item.AuxPrice = list[i].Price || 0
              item.AuxSalesIntegral = list[i].Integral || 0
              item.AuxQty = that.fomatFloat(item.ReableMaxQty / item.AuxRate, that.data.quantityDigits)
              item.UnitPrice = list[i].Price || 0
              break
            }
          }
        }
        return item
      })
      let retreatType = ['退货', '换货'];
      if(retreatInfo.ReType == 1){
        retreatType = ['退货'];
      }
      let rewayArray = ['退货退款','仅退款'];
      if(retreatInfo.RefundWay == 0){
        rewayArray = ['退货退款'];
      }else if(retreatInfo.RefundWay == 1){
        rewayArray = ['仅退款'];
      }
      that.setData({
        retreatInfo: retreatInfo,
        goodslist: goodslist,
        orderId: orderid,
        backWayList: backWayList,
        backWayArray: backWayArray,
        reasonList: reasonList,
        reasonArray: reasonArray,
        retreatType: retreatType,
        rewayArray: rewayArray,
        backWayIndex: backWayIndex,
        RefundChannel: refundChannel
      }, () => {
        that.getAccount();
      });
    });
  },
  /**
   * 获得银行帐号
   */
  getAccount:function(){
    var that = this;
    finance.get_account_list(function(res){
      var bankArray=['请选择银行帐号'],bankList=[{Id:0,Name:'',BankName:'',BlockAccount:''}],bankIndex=0,
      wechatArray = ['请选择微信账号'],wechatList = [{Id:0,Name:'',BlockAccount:''}],wechatIndex=0,
      alipayArray = ['请选择支付宝帐号'],alipayList = [{Id:0,Name:'',BlockAccount:''}],alipayIndex=0;
      for(var i=0;i<res.length;i++){
        let item = res[i];
        //银行账户
        if(item.AccountType == 1 && item.Status == 1){
          bankArray.push(item.Name + "-" + (item.BankName || '') + "-" + item.BlockAccount);
          bankList.push(res[i]);
        }
        //微信
        else if(item.AccountType == 6 && item.Status == 1){
          wechatArray.push(item.Name+'-'+item.BlockAccount)
          wechatList.push(res[i]);
        }
        //支付宝
        else if(item.AccountType == 7 && item.Status == 1){
          alipayArray.push(item.Name+'-'+item.BlockAccount)
          alipayList.push(res[i]);
        }
      }
      if (bankList.length>0) {
        for (let i = 0; i < bankList.length; i++) {
          if (bankList[i].IsDefault == 1) {
            bankIndex = i;
          }
        }
      }
      if (wechatList.length>0) {
        for (let i = 0; i < wechatList.length; i++) {
          if (wechatList[i].IsDefault == 1) {
            wechatIndex = i;
          }
        }
      }
      if (alipayList.length>0) {
        for (let i = 0; i < alipayList.length; i++) {
          if (alipayList[i].IsDefault == 1) {
            alipayIndex = i;
          }
        }
      }
      that.setData({
        bankList:bankList,
        bankArray:bankArray,
        bankIndex:bankIndex,
        wechatArray:wechatArray,
        wechatList:wechatList,
        wechatIndex:wechatIndex,
        alipayArray:alipayArray,
        alipayList:alipayList,
        alipayIndex:alipayIndex
      });
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      Currency:api.Currency || '￥'
    })
    var account = this.data.account;
    if (account==null||account.Id==undefined) return;
    if (account.AccountType == 1 && account.Status == 1) {
      account.BlockAccount=account.Account;
      this.data.bankArray.push(account.Name + "-" + account.BankName + "-" + account.Account);
      this.data.bankList.push(account);
      this.data.bankIndex = this.data.bankList.length-1;
    }
    this.setData({
      bankArray:this.data.bankArray,
      bankList:this.data.bankList,
      bankIndex:this.data.bankIndex,
      account:null
    });
  },
  /**加载配置项参数 */
  getWholesaleConfig() {
    var that = this;
    var config = wholesaleSettings.getConfig();
    that.setData({
      quantityDigits: config.quantityDigits <= 2 ? 2 : 4,
      priceDigits: config.priceDigits
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
  * 页面相关事件处理函数--监听用户下拉动作
  */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
    this.getDetail(this.data.oddNumber);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**
  * 修改退换货描述
  */
  bindChangeReason: function (e) {
    this.setData({reason: e.detail.value});
  },
  /**
   * 退款渠道选择
   */
  onBackWayChangeEvent: function (e) {
    var {backWayList,bankIndex,bankList,wechatIndex,wechatList,alipayIndex,alipayList} = this.data;
    var backWayIndex = e.detail.value;
    var refundChannel = backWayList[backWayIndex].Id;
    if (refundChannel==1&&bankIndex==0&&bankList.length>0) {
      for (let i = 0; i < bankList.length; i++) {
        if (bankList[i].IsDefault == 1) {
          bankIndex = i;
        }
      }
    }else if (refundChannel==6&&wechatIndex==0&&wechatList.length>0) {
      for (let i = 0; i < wechatList.length; i++) {
        if (wechatList[i].IsDefault == 1) {
          wechatIndex = i;
        }
      }
    }else if (refundChannel==7&&alipayIndex==0&&alipayList.length>0) {
      for (let i = 0; i < alipayList.length; i++) {
        if (alipayList[i].IsDefault == 1) {
          alipayIndex = i;
        }
      }
    }
    this.setData({
      backWayIndex: backWayIndex,
      RefundChannel: refundChannel,
      bankIndex: bankIndex,
      wechatIndex: wechatIndex,
      alipayIndex: alipayIndex,
    });
  },
  onReasonChangeEvent(e){
    var {reason, reasonIndex, reasonArray} = this.data;
    reasonIndex = e.detail.value || 0;
    if (reasonIndex>0) {
      reason = reasonArray[reasonIndex] || '';
    }else{
      reason = '';
    }
    this.setData({
      reason: reason,
      reasonIndex: reasonIndex
    })
  },
  onRewayChangeEvent(e){
    this.setData({
      rewayIndex:e.detail.value
    })
  },
  onBankChangeEvent:function(e){
    this.setData({
      bankIndex: e.detail.value
    });
  },
  onWechatChangeEvent:function(e){
    this.setData({
      wechatIndex: e.detail.value
    });
  },
  onAlipayChangeEvent:function(e){
    this.setData({
      alipayIndex: e.detail.value
    });
  },
  /**
   * 选择售后类型
   */
  choseRetreatType: function (e) {
    var txt = e.currentTarget.dataset.name;
    if(this.data.retreatInfo.ReType == 1 && txt == '换货')return;
    var isReturn=true;
    if (txt == '换货') {
      isReturn=false;
    }
    this.setData({
      isReturn: isReturn,
      retreatTypeId: e.currentTarget.dataset.index
    });
  },
  /**
   * 数量切换
   */
  onNumChage: function (e) {
    var index = e.detail.idx;
    var num = e.detail.value;
    if (num < 0) return;
    let goodslist = this.data.goodslist
    var item = goodslist[index]
    console.log(item, index, num)
    item.AuxQty = num
    goodslist[index] = item
    this.setData({
      goodslist: goodslist
    })
    this.caculate()
  },
  /**
   * 计算
   */
  caculate:function(){
    var that=this;
    let {
      goodslist,
      quantityDigits
    } = this.data
    var payable_price = 0, category_num = 0, quantity = 0, itemxml = [];
    for (var i = 0; i < goodslist.length; i++) {
      var item = goodslist[i];
      if (!item.IsChecked) continue;
      category_num += 1;
      let itemQuantity = this.fomatFloat(item.AuxQty * item.AuxRate, quantityDigits)
      if (item.ReableMaxQty > 0 && itemQuantity > item.ReableMaxQty) {
        itemQuantity = item.ReableMaxQty
      }
      let itemAuxQty = this.fomatFloat(itemQuantity / item.AuxRate, quantityDigits)
      let totalAmount = item.AuxQty * item.AuxPrice;
      if (item.ReableMaxAmount > 0 && totalAmount >= item.ReableMaxAmount) {
        totalAmount = item.ReableMaxAmount;
      }
      payable_price += totalAmount;
      quantity += itemQuantity;
      itemxml.push(`
      <item>
        <ItemId>${item.Id}</ItemId>
        <GoodsId>${item.GoodsId}</GoodsId>
        <Quantity>${itemQuantity.toFixed(quantityDigits)}</Quantity>
        <OrderId>${item.OrderId}</OrderId>
        <AuxQty>${itemAuxQty}</AuxQty>
        <AuxRate>${item.AuxRate}</AuxRate>
        <AuxUnit>${item.AuxUnit}</AuxUnit>
      </item>`);
      
    }
    that.setData({
      caculate_info:{
        category_num: category_num,
        quantity: quantity,
        payable_price: payable_price.toFixed(2),
        itemxml: itemxml.join("")
      }
    });
  },
  /**
   * 选择待申请的商品
   */
  onSelectGoodsEvent: function (e) {
    var that=this;
    var _array = e.detail.value;
    for (var i = 0; i < that.data.goodslist.length; i++) {
      that.data.goodslist[i].IsChecked=false;
    }
    for(var i=0;i<_array.length;i++){
      that.data.goodslist[_array[i]].IsChecked=true;
    }
    this.caculate(false);
    if (_array.length > 0) {
      this.setData({
        showFooter: false
      });
    } else {
      this.setData({
        showFooter: true,
      });
    }
  },
  /**
   * 提交申请
   */
  onSubmitEvent:function(e){
    var that=this;
    var isSelectGoods=false;
    let payable_price = that.data.caculate_info.payable_price;
    for (var i = 0; i < that.data.goodslist.length; i++) {
      if(that.data.goodslist[i].IsChecked)
      {
        isSelectGoods=true;
        break;
      }
    }
    if(!isSelectGoods){
      util.tips("请选择货品");
      return;
    }
    var reason = that.data.reason;
    if (reason=='') {
      util.tips("请填写退换货描述");
      return;
    }
    if (that.data.isReturn && payable_price>0){
      if (that.data.backWayIndex ==0 && that.data.retreatInfo.IsPaid==1){
        util.tips("请选择退款渠道");
        return;
      }
      if (that.data.RefundChannel == 1 && that.data.bankIndex==0){
        util.tips("请选择开户银行");
        return;
      }
      if(that.data.RefundChannel == 6){//微信
        if(!that.data.wechatArray[that.data.wechatIndex]){
          util.tips("请选择微信账号");
          return;
        }
      }
      if(that.data.RefundChannel == 7){//支付宝
        if(!that.data.alipayArray[that.data.alipayIndex]){
          util.tips("请选择支付宝账号");
          return;
        }
      }
    }
    var AccountId = '';
    if(that.data.RefundChannel == 6){
      AccountId = '<CashAccountId>'+that.data.wechatList[that.data.wechatIndex].Id+'</CashAccountId>';
    }else if(that.data.RefundChannel == 7){
      AccountId = '<CashAccountId>'+that.data.alipayList[that.data.alipayIndex].Id+'</CashAccountId>';
    }else if(that.data.RefundChannel == 1){
      AccountId = '<CashAccountId>'+that.data.bankList[that.data.bankIndex].Id+'</CashAccountId>';
    }
    var main_str = `
      <Reason><![CDATA[${reason}]]></Reason>
      <OrderId>${that.data.orderId}</OrderId>
      <ReWay>${that.data.retreatInfo.RefundWay==2?that.data.rewayIndex:that.data.retreatInfo.RefundWay}</ReWay>
      <ReType>${(that.data.isReturn ? 1 : 2)}</ReType>
    `;
    var fdata=`
      <amount>${that.data.caculate_info.payable_price}</amount>
      <RefundType>${that.data.retreatInfo.IsPaid == 0?4:that.data.RefundChannel}</RefundType>
      ${(AccountId || '')}
    `;
    if(that.data.RefundChannel == 1){
      var bank=that.data.bankList[that.data.bankIndex];
      fdata += `
      <BankName>${bank.BankName}</BankName>
      <AccountName>${bank.Name}</AccountName>
      <Account>${bank.BlockAccount}</Account>`;
    }
    fdata+= ` <Items>${that.data.caculate_info.itemxml}</Items>`;
    if (that.data.isReturn) {
      fdata = `<Refund>${fdata}</Refund>`
    }
    fdata = `${main_str}<ContextXml>${fdata}</ContextXml>`;
    retreat.submitApply(fdata);
  },
  /**
   * 改变单位
   */
  onChangeGoodsUnitEvent: function (e) {
    var that = this;
    //获取当前商品的索引
    var index = e.detail.value;  
    var gidx = e.currentTarget.dataset.gidx;
    let goodslist = this.data.goodslist
    var goods = goodslist[gidx]
    let chiocegoods = {}
    if (goods.auxiliaryunits) {
      chiocegoods = goods.auxiliaryunits[index] || {}
    }
    goods.unitindex = index
    goods.AuxRate = chiocegoods.Translated || goods.AuxRate
    goods.AuxUnit = chiocegoods.Name || goods.AuxUnit
    goods.AuxPrice = chiocegoods.Price || 0
    goods.AuxSalesIntegral = chiocegoods.Integral || 0
    goods.AuxQty = this.fomatFloat(goods.ReableMaxQty / goods.AuxRate, this.data.quantityDigits)
    goods.UnitPrice = chiocegoods.Price || 0
    goodslist[gidx] = goods
    this.setData({
      goodslist: goodslist
    }, function () {
      that.caculate()
    })
  },
  fomatFloat(src,pos){
    return Math.round(src*Math.pow(10, pos))/Math.pow(10, pos);
  },
  show(){
    this.setData({
      modelAccount:true
    })
  },
  //关闭添加账号
  close(){
    this.setData({
      modelAccount:false
    })
  },
  //开关
  onSwitch(e){
    this.setData({
      switch:e.detail.value?1:0
    })
  },
  onStatus(e){
    this.setData({
     status:e.detail.value?1:0
    })
  },
  //账号
  iptAccount(e){
    this.setData({
      accountName:e.detail.value
    })
  },
  //姓名
  iptName(e){
    this.setData({
      userName:e.detail.value
    })
  },
  //收款二维码
  bindUploadSign(){
    var that=this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album'],
      success: function (res) {
        var tempFilePaths = res.tempFilePaths;
        var data = {num:3001,type:3,tempFilePaths:tempFilePaths};
        upload.upload_image_server(data, function (image_list) {
          if (image_list.length==0){
            util.alert("上传失败");
            return;
          }
          that.setData({
            ImgSrc: image_list.join(",")
          });
        })
      }
    });
  },
  //删除
  onDelImageEvent(){
    this.setData({
      ImgSrc: ''
    });
  },
  //添加账号--保存
  onSubmitSave(){
    var that = this;
    //开关 this.data.switch
    //账号 this.data.accountName
    //姓名 this.data.userName
    //收款二维码 this.data.ImgSrc
    //退款路径 this.data.RefundChannel
    if(!that.data.accountName){
      util.tips('请输入账号');
      return
    }
    var data = {
      AccountType:that.data.RefundChannel,
      Account:that.data.accountName,
      IsDefault:that.data.switch,
      Status:that.data.status,
      ImgSrc:that.data.ImgSrc,
      Name:that.data.userName
    }
    finance.getAddAccount(data,function(res){
      that.setData({
        modelAccount:false,
        accountName:'',
        userName:'',
        switch:1,//开关-默认账号
        status:0,//开关-状态
        ImgSrc:''
      })
      that.getAccount();
    });
  },
})